// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

package com.netease.yunxin.kit.conversationkit.ui.page;


import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;
import static com.netease.yunxin.kit.conversationkit.ui.view.ConversationAdapter.imOfficialBean;

import android.animation.LayoutTransition;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.angcyo.tablayout.delegate2.ViewPager2Delegate;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.jeremyliao.liveeventbus.utils.AppUtils;
import com.luoxiang.lib_common.bean.NumberBean;
import com.luoxiang.lib_common.utils.MmkvUtil;
import com.luoxiang.lib_common.utils.NetUtils;
import com.lxj.xpopup.XPopup;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.yunxin.kit.common.ui.fragments.BaseFragment;
import com.netease.yunxin.kit.common.utils.NetworkUtils;
import com.netease.yunxin.kit.conversationkit.ui.databinding.ConversationFragmentBinding;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * conversation list fragment show your recent conversation
 */
public class ConversationFragment extends BaseFragment {

    private ConversationFragmentBinding viewBinding;

    private Boolean mSecondHide = false;

    @Nullable
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        viewBinding = ConversationFragmentBinding.inflate(inflater, container, false);
        return viewBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        NetworkUtils.registerNetworkStatusChangedListener(networkStateListener);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (NotificationManagerCompat.from(requireContext()).areNotificationsEnabled()) {
            viewBinding.constraintNotification.setVisibility(View.GONE);
        }
    }

    private void initView() {
        UltimateBarX.addStatusBarTopPadding(viewBinding.tab);
        UltimateBarX.addStatusBarTopPadding(viewBinding.imageMore);
        viewBinding.linearIM.setLayoutTransition(new LayoutTransition());
        viewBinding.buttonOpen.setOnClickListener(v -> {
            goNotificationSetting();
        });
        viewBinding.imageClose.setOnClickListener(v -> {
            viewBinding.constraintNotification.setVisibility(View.GONE);
        });
        viewBinding.imageMore.setOnClickListener(view -> new XPopup.Builder(getContext())
                .atView(viewBinding.imageMore)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                .asAttachList(new String[]{"清空消息", "一键已读"},
                        null,
                        (position, text) -> {
                            if (position == 0) {
                                LiveEventBus.get("OneClickRead").post(true);
                            } else {
                                NIMClient.getService(MsgService.class).clearAllUnreadCount();
                            }
                            if (imOfficialBean == null) return;
                            imOfficialBean.getData().getOfficialMsgInfo().getNewestMsg().setNotRead(0);
                            NetUtils.getInstance().getApiService().officialMessage(MmkvUtil.INSTANCE.decodeString(TOKEN), 1, 100)
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new io.reactivex.Observer<NumberBean>() {
                                        @Override
                                        public void onSubscribe(Disposable d) {
                                        }

                                        @Override
                                        public void onNext(NumberBean numberBean) {
                                            LiveEventBus.get("RefreshNoReading").post(null);
                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                        }

                                        @Override
                                        public void onComplete() {
                                        }
                                    });
                            LiveEventBus.get("fetchConversation").post(true);
                        })
                .show());
        viewBinding.viewPager.setAdapter(new FragmentStateAdapter(getChildFragmentManager(), getLifecycle()) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                if (position == 0) {
                    return new ConversationCallSubFragment();
                }
                return new ConversationCallFragment();
            }

            @Override
            public int getItemCount() {
                return 2;
            }
        });
        ViewPager2Delegate.Companion.install(viewBinding.viewPager, viewBinding.tab, null);
        LiveEventBus.get("HIDE", Boolean.class).observe(this, s -> {
            mSecondHide = s;
            if (s) {
                viewBinding.imageMore.setVisibility(View.INVISIBLE);
            } else {
                viewBinding.imageMore.setVisibility(View.VISIBLE);
            }
        });
        viewBinding.viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (position == 1) {
                    viewBinding.imageMore.setVisibility(View.INVISIBLE);
                } else {
                    if (mSecondHide) {
                        viewBinding.imageMore.setVisibility(View.INVISIBLE);
                    } else {
                        viewBinding.imageMore.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }

    /**
     * 前往通知设置页面
     */
    private void goNotificationSetting() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        intent.setData(Uri.fromParts("package", AppUtils.getApp().getPackageName(), null));
        startActivity(intent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        NetworkUtils.unregisterNetworkStatusChangedListener(networkStateListener);
    }

    private final NetworkUtils.NetworkStateListener networkStateListener =
            new NetworkUtils.NetworkStateListener() {
                @Override
                public void onAvailable(NetworkInfo network) {
                    if (viewBinding == null) {
                        return;
                    }
                    viewBinding.conversationNetworkErrorTv.setVisibility(View.GONE);
                }

                @Override
                public void onLost(NetworkInfo network) {
                    if (viewBinding == null || NetworkUtils.isConnected()) {
                        return;
                    }
                    viewBinding.conversationNetworkErrorTv.setVisibility(View.VISIBLE);
                }
            };
}
